<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\MemberShip;
use App\Models\Shareholder;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

class UploadService
{

    /*
     * 会员证书上传
     * */
    public static function membership($request)
    {
        $ticket = IT('ticket', true);
        $content = IT('img_url', true, '未知上传内容', 10162);
        $mobile_unique_code = IT('mobile_unique_code', true, '未知操作设备', 10163);
        //$member_avatar = IT('member_avatar');

        $user_info = User::getUserInfo($ticket);
        if (!$user_info)
            EE('用户未登录', 1000, 10004);
        if(empty($user_info->mobile))
            return ['status'=>'error', 'message_code'=>10164, 'message'=>'用户手机号不存在'];
        $memberShipRows = MemberShip::getRows([['mobile', '=', $user_info->mobile], ['status', '=', '0']]);
        if(empty($memberShipRows))
            return ['status'=>'error', 'message_code'=>10165, 'message'=>'会员不存在'];
        if(empty(Redis::get('membership:'.$user_info->uid)))
            return ['status'=>'error', 'message_code'=>10166, 'message'=>'请上传会员头像'];

        $type = empty(config('params.upload_file_type.0')) ? 'membership':config('params.upload_file_type.0');
        $path = base_path('storage/'.$type.'/'.$user_info->id.'/');

        $check = checkPath($path);
        // 检测创建目录
        if(!$check)
            return ['status'=>'error', 'message_code'=>10139,'message'=>'目录不存在'];

        // 本地服务器保存文件
        $file = $path.date('Ymd') . md5(uniqid().$type).'.txt';
        file_put_contents($file, $content, FILE_APPEND);
        if(!file_exists($file))
            return ['status'=>'error', 'message_code'=>10160, 'message'=>'上传失败'];

        // 上传文件
        $uploadOssPath = $type.'/'.substr(md5($mobile_unique_code), 0, 4) . '/' . date('Ymd') . '/' . date('Ymd') . md5(uniqid().$type).'.text';
        $uploadRest = Sts::fileUpload($file, $uploadOssPath);
        // 上传文件成功
        if(isset($uploadRest['status']) && $uploadRest['status'] == 'success' && !empty($uploadRest['data']['info']['url'])){
            $member_avatar = Redis::get('membership:'.$user_info->uid);
            $memberShipRows->certificate = $uploadRest['data']['info']['url'];
            $memberShipRows->member_avatar = $member_avatar;
            $memberShipRows->updated_at = time2date();
            if(!$memberShipRows->save())
                return ['status'=>'error', 'message_code'=>10167, 'message'=>'保存失败'];

            Redis::del('membership:'.$user_info->uid);
        }

        return $uploadRest;
    }

    /*
     * 签名上传
     * */
    public static function shareholder_sign($request)
    {
        $ticket = IT('ticket', true);
        $mobile_unique_code = IT('mobile_unique_code', true, '未知操作设备');
        $content = IT('img_url', true, '未知上传内容');
        $user_info = User::getUserInfo($ticket);
        if (!$user_info)
            EE('用户未登录', 1000);
        if(empty($user_info->mobile))
            return ['status'=>'error', 'message'=>'用户手机号不存在'];

        $shareholderModel = Shareholder::where([['mobile', '=', $user_info->mobile]])->orderBy('id', 'desc')->first();
        if(empty($shareholderModel) || $shareholderModel->status == 1)
            return ['status'=>'error', 'message'=>'股东用户不存在'];
        if($shareholderModel->operation_status == 2 )
            return ['status'=>'error', 'message'=>'不能重复签名'];
        if(empty($shareholderModel->is_card) && $shareholderModel->operation_status != 1)
            return ['status'=>'error', 'message'=>'资料未完善或已签名'];

        $type = empty(config('params.upload_file_type.1')) ? 'membership':config('params.upload_file_type.1');
        $path = base_path('storage/'.$type.'/'.$user_info->id.'/');

        $check = checkPath($path);
        // 检测创建目录
        if(!$check)
            return ['status'=>'error', 'message'=>'目录不存在'];

        // 本地服务器保存文件
        /*$tt = $path.date('Ymd') . md5(uniqid().$type).'.txt';
        file_put_contents($tt, $content, FILE_APPEND);*/

        // 转换base64 图片
        $file = $path.date('Ymd') . md5(uniqid().$type).'.png';
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result);
        if(!isset($result) || empty($result))
            return ['status'=>'error', 'message'=>'签名文件格式有误'];
        $type = $result[2];
        file_put_contents($file, base64_decode(str_replace($result[1], '', $content))); //对图片进行解析并保存

        if(!file_exists($file))
            return ['status'=>'error', 'message'=>'上传失败'];

        // 上传文件
        $uploadOssPath = substr(md5($mobile_unique_code), 0, 4) .'/images/sign/' . date('Ymd') . '/' . date('Ymd') . md5(uniqid().$type).'.png';
        $uploadRest = Sts::fileUpload($file, $uploadOssPath);

        // 上传文件成功
        if(isset($uploadRest['status']) && $uploadRest['status'] == 'success' && !empty($uploadRest['data']['info']['url'])){
            $shareholderModel->sign_img = $uploadRest['data']['info']['url'];
            $shareholderModel->operation_status = 2;
            if($shareholderModel->save())
                return ['status'=>'success', 'message'=>'操作成功'];
        }
        return ['status'=>'error', 'message'=>'上传失败'];
    }

    /*
     * 协议书上传
     * */
    public static function shareholder_agreement($request)
    {
        $ticket = IT('ticket', true);
        $content = IT('img_url', true, '未知上传内容', 10162);
        $mobile_unique_code = IT('mobile_unique_code', true, '未知操作设备', 10163);

        $user_info = User::getUserInfo($ticket);
        if (!$user_info)
            EE('用户未登录', 1000, 10004);
        if(empty($user_info->mobile))
            return ['status'=>'error', 'message_code'=>10164, 'message'=>'用户手机号不存在'];
        $ShareholderRows = Shareholder::where([['mobile','=',$user_info->mobile]])->orderBy('id', 'desc')->first();
        if(empty($ShareholderRows) || $ShareholderRows->status == 1)
            return ['status'=>'error', 'message_code'=>10165, 'message'=>'会员不存在'];
        if($ShareholderRows->operation_status != '2')
            return ['status'=>'error', 'message_code'=>10168, 'message'=>'未签名'];

        $type = empty(config('params.upload_file_type.2')) ? 'membership':config('params.upload_file_type.2');
        $path = base_path('storage/'.$type.'/'.$user_info->id.'/');

        $check = checkPath($path);
        // 检测创建目录
        if(!$check)
            return ['status'=>'error', 'message_code'=>10139, 'message'=>'目录不存在'];

        // 本地文件
        $temp_arr = [];
        $local_temp_arr = [];
        foreach ($content as $key=>$value) {
            // 本地服务器保存文件
            $file = $path.'/'.date('Ymd') . md5(uniqid().$type.$key).'.txt';
            file_put_contents($file, $value, FILE_APPEND);
            if(!file_exists($file))
                return ['status'=>'error', 'message_code'=>10160, 'message'=>'上传失败'];

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 上传文件   ---可以抽出来队列跑
            $uploadOssPath = $type.'/'.substr(md5($mobile_unique_code), 0, 4) . '/' . date('Ymd') . '/' . date('Ymd') . md5(uniqid().$type.$key).'.text';
            $uploadRest = Sts::fileUpload($file, $uploadOssPath);
            $local_temp_arr[] = $file;

            // 上传文件成功
            if(isset($uploadRest['status']) && $uploadRest['status'] == 'success' && !empty($uploadRest['data']['info']['url'])){
                $temp_arr[] = $uploadRest['data']['info']['url'];
                // 存储数据库
                if(count($temp_arr) == 5){
                    //$temp_arr[] = config('params.licence_txt');
                    $ShareholderRows->local_agree_img = implode(',', $local_temp_arr);
                    $ShareholderRows->shareholder_agree_img = implode(',', $temp_arr);
                    if(!$ShareholderRows->save())
                        return ['status'=>'error', 'message_code'=>10169, 'message'=>'上传协议失败'];
                }
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        return $uploadRest;
    }

    /*
     * 股东证书上传
     * */
    public static function shareholder_certificate($request)
    {

        $ticket = IT('ticket', true);
        $content = IT('img_url', true, '未知上传内容', 10162);
        $mobile_unique_code = IT('mobile_unique_code', true, '未知操作设备', 10163);

        $user_info = User::getUserInfo($ticket);
        if (!$user_info)
            EE('用户未登录', 1000, 10004);
        if(empty($user_info->mobile))
            return ['status'=>'error', 'message_code'=>10164, 'message'=>'用户手机号不存在'];
        $ShareholderRows = Shareholder::getRows([['mobile', '=', $user_info->mobile], ['status', '=', '0']]);
        if(empty($ShareholderRows))
            return ['status'=>'error', 'message_code'=>10170, 'message'=>'股东不存在'];
        if($ShareholderRows->operation_status != '2')
            return ['status'=>'error', 'message_code'=>10168, 'message'=>'未签名'];

        $type = empty(config('params.upload_file_type.3')) ? 'membership':config('params.upload_file_type.3');
        $path = base_path('storage/'.$type.'/'.$user_info->id.'/');
        $check = checkPath($path);
        // 检测创建目录
        if(!$check)
            return ['status'=>'error', 'message_code'=>10139, 'message'=>'目录不存在'];

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 上传文件   ---可以抽出来队列跑
        // 本地文件
        $temp_arr = [];
        $local_temp_arr = [];
        foreach ($content as $key=>$value) {
            // 本地服务器保存文件
            $file = $path.'/'.date('Ymd') . md5(uniqid().$type.$key).'.txt';
            file_put_contents($file, $value, FILE_APPEND);
            if(!file_exists($file))
                return ['status'=>'error', 'message_code'=>10160, 'message'=>'上传失败'];

            $uploadOssPath = $type.'/'.substr(md5($mobile_unique_code), 0, 4) . '/' . date('Ymd') . '/' . date('Ymd') . md5(uniqid().$type.$key).'.text';
            $uploadRest = Sts::fileUpload($file, $uploadOssPath);
            // 上传文件成功
            if(isset($uploadRest['status']) && $uploadRest['status'] == 'success' && !empty($uploadRest['data']['info']['url'])){
                $temp_arr[] = $uploadRest['data']['info']['url'];
                $local_temp_arr[] = $file;
                if(count($temp_arr) == 2){
                    $ShareholderRows->local_certificate_img = implode(',', $local_temp_arr);
                    $ShareholderRows->shareholder_certificate_img = implode(',', $temp_arr);
                    if(!$ShareholderRows->save())
                        return ['status'=>'error', 'message_code'=>10171, 'message'=>'上传股东证书失败'];
                }
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        return $uploadRest;
    }

    /*
     * 会员证头像
     * */
    public static function member_avatar($request)
    {
        $ticket = IT('ticket', true);
        $mobile_unique_code = IT('mobile_unique_code', true, '未知操作设备', 10163);
        $img_url = IT('img_url', true, '请上传会员头像', 10166);

        $user_info = User::getUserInfo($ticket);
        if (!$user_info)
            return ['status'=>'error', 'message_code'=>10004, 'message'=>'用户未登录'];
        if(empty($user_info->mobile))
            return ['status'=>'error', 'message_code'=>10164, 'message'=>'用户手机号不存在'];
        $membership = MemberShip::getRows([['mobile', '=', $user_info->mobile], ['status', '=', '0']]);
        if(empty($membership))
            return ['status'=>'error', 'message_code'=>10165, 'message'=>'会员不存在'];

        Redis::setex('membership:'.$user_info->uid, 300, $img_url);

        $img_url_new = '';
        if(!empty($img_url)){
            $img_url_arr = explode('.com/', getSignUrl($img_url));
            if(count($img_url_arr) > 1)
                $img_url_new = env('IMAGE_PROXY_URL').'/'.$img_url_arr[1];
        }

        return ['status'=>'success', 'message_code'=>10000, 'message'=>'操作成功', 'data'=>$img_url_new];
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

}